package cn.wangchao.org.service.impl;

import cn.wangchao.basic.service.impl.BaseServiceImpl;
import cn.wangchao.org.domain.Department;
import cn.wangchao.org.mapper.DepartmentMapper;
import cn.wangchao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    public void update(Department department) {
        String dirPath = "";
        if (department.getParent()==null){
            //顶级
            dirPath = "/"+department.getId();
        }else {
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);

        departmentMapper.update(department);
    }

    @Override
    public List<Department> findparent() {
        //查询出来所有数据
        List<Department> departments = departmentMapper.loadAll();
        //创建hashmap空对象
        HashMap<Long, Department> allDepts = new HashMap<>();
        //遍历取出值
        for (Department department : departments) {
            //给hashmap存值,key就是id,value就是department对象
            allDepts.put(department.getId(), department);

        }
        //顶级部门
        List<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            if (tmp.getParent_id()==null){
                firstDepts.add(tmp);
            }else {
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent!=null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }
}
